/*
    This file is part of the open source IVMP-MySQL project.

    IVMP-MySQL is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    IVMP-MySQL is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with IVMP-MySQL.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
	File: Logger.cpp

	Description:
		Contains the class definitions for Logger.h (see documentation
		of that file for more information).
*/

#include <Logger.h>
#include <sstream>
#include <time.h>
#include <SDK/SDK.h>
#include <stdarg.h>

// Static variables
FILE* Logger::LogFile = NULL;

void Logger::Initialise()
{
	if (LogFile)
		return;

	LogFile = fopen("ivmp-mysql.log", "w");
}

void Logger::Close()
{
	if (LogFile)
		fclose(LogFile);
}

void Logger::Out(const char* string, bool logToConsole)
{
	char tbuf[11];
	time_t t = time(NULL);
	tm* lt = localtime(&t);
	sprintf(tbuf, "[%02d:%02d:%02d]", lt->tm_hour, lt->tm_min, lt->tm_sec);

	if (LogFile)
	{
		fprintf(LogFile, "%s %s\n", tbuf, string);
		fflush(LogFile);
	}

	if (logToConsole)
	{
		LogPrintf("[MySQL] %s", string);
	}
}

void Logger::OutFormat(const char* string, ...)
{
	char buf[512];

	va_list args;
	va_start(args, string);
	vsnprintf(buf, sizeof(buf), string, args);
	va_end(args);

	Logger::Out(buf, false);
}

void Logger::OutFormatConsole(const char* string, ...)
{
	char buf[512];

	va_list args;
	va_start(args, string);
	vsnprintf(buf, sizeof(buf), string, args);
	va_end(args);

	Logger::Out(buf, true);
}